<template>
  <h2>公告通知</h2>
  <div class="notice-container">
    <!-- 搜索和添加区域 -->
    <el-row :gutter="20" class="search-bar">
      <el-col :span="8">
        <el-input
            v-model="title"
            placeholder="请输入公告标题"
        ></el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="loadNotices">查询</el-button>
        <el-button type="success" @click="handleAdd">新增公告</el-button>
      </el-col>
    </el-row>

    <!-- 公告列表 -->
    <div class="notice-list">
      <div class="notice-item" v-for="(notice, index) in page.list" :key="notice.id || index">
        <div class="notice-date">
          <div class="day">{{ formatDate(notice.time).day }}</div>
          <div class="month-year">{{ formatDate(notice.time).monthYear }}</div>
        </div>
        <div class="notice-content">
          <h3 class="notice-title">{{ notice.title }}</h3>
          <p class="notice-text">{{ notice.desc }}</p>
        </div>
        <div class="notice-actions">
          <el-button size="small" @click="handleEdit(notice)">编 辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(notice.id)">删 除</el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <el-pagination
        v-if="page.total > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        class="pagination"
    ></el-pagination>

    <!-- 新增对话框 -->
    <el-dialog
        title="新增公告"
        v-model="addDialogVisible"
        width="50%"
    >
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="desc">
          <el-input
              type="textarea"
              v-model="addForm.desc"
              :rows="5"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
        title="编辑公告"
        v-model="editDialogVisible"
        width="50%"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="desc">
          <el-input
              type="textarea"
              v-model="editForm.desc"
              :rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker
              v-model="editForm.time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              readonly
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 分页数据
const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 新增表单数据
const addForm = reactive({
  title: '',
  desc: '',
  // time: new Date()
})
// 新增表单验证规则
const addRules = reactive({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, message: '至少输入 10 个字符', trigger: 'blur' }
  ]
})
const addFormRef = ref(null)
const addDialogVisible = ref(false)

// 编辑表单数据
const editForm = reactive({
  id: null,
  title: '',
  desc: '',
  time: new Date()
})
// 编辑表单验证规则（可复用新增规则，也可单独定义）
const editRules = reactive({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, message: '至少输入 10 个字符', trigger: 'blur' }
  ],
  time: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ]
})
const editFormRef = ref(null)
const editDialogVisible = ref(false)

// 搜索关键词
const title = ref('')
const id=ref(0)

// 日期格式化
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return {
    day: date.getDate().toString(),
    monthYear: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`
  }
}

// 加载公告列表
const loadNotices = () => {
  axios.get('/notice/list', {
    params: {
      title: title.value,
      pageNum: page.value.pageNum,
      pageSize: page.value.pageSize
    }
  })
      .then(res => {
        page.value = res.data
      })
      .catch(error => {
        console.error('加载公告失败:', error)
        ElMessage.error('加载公告失败')
      })
}

// 分页相关
const handleSizeChange = (val) => {
  page.value.pageSize = val
  loadNotices()
}

const handleCurrentChange = (val) => {
  page.value.pageNum = val
  loadNotices()
}

// 新增公告：打开新增对话框并初始化表单
const handleAdd = () => {
  addForm.title = ''
  addForm.desc = ''
  // addForm.time = new Date()
  addDialogVisible.value = true
}

// 编辑公告：打开编辑对话框并赋值表单
const handleEdit = (notice) => {
  editForm.id = notice.id
  editForm.title = notice.title
  editForm.desc = notice.desc || notice.desc
  editForm.time = notice.time
  editDialogVisible.value = true
}

// 提交新增表单
const submitAdd = () => {
  addFormRef.value.validate((valid) => {
    console.log('准备发送的数据:', JSON.stringify(addForm, null, 2))
    if (valid) {
      axios.post('/notice/add', addForm)
          .then(response => {
            if (response.data.code===200) {
              ElMessage.success('添加成功')
              addDialogVisible.value = false
              loadNotices()
            } else {
              ElMessage.error(response.data.msg || '操作失败')
            }
          })
          .catch(error => {
            console.error('新增表单提交失败:', error)
            ElMessage.error('操作失败')
          })
    } else {
      console.log('验证失败')
      return false
    }
  })
}

// 提交编辑表单
const submitEdit = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      console.log('准备发送的数据:', JSON.stringify(editForm, null, 2))
      axios.post('/notice/add', editForm)
          .then(response => {
            if (response.data.code===200) {
              ElMessage.success('修改成功')
              editDialogVisible.value = false
              loadNotices()
            } else {
              ElMessage.error(response.data.msg|| '操作失败')
            }
          })
          .catch(error => {
            console.error('编辑表单提交失败:', error)
            ElMessage.error('操作失败')
          })
    } else {
      console.log('验证失败')
      return false
    }
  })
}

// 删除公告
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该公告吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        console.log('准备发送的数据:', JSON.stringify(id, null, 2))
        axios.post('/notice/delete?id='+id)
            .then(response => {
              if (response.data.code===200) {
                ElMessage.success('删除成功')
                loadNotices()
              } else {
                ElMessage.error(response.data.msg || '删除失败')
              }
            })
            .catch(error => {
              console.error('删除失败:', error)
              ElMessage.error('删除失败')
            })
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

// 初始化加载
onMounted(() => {
  loadNotices()
})
</script>

<style scoped>
/* 样式保持不变 */
h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.notice-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.notice-list {
  margin-top: 20px;
}

.notice-item {
  display: flex;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.notice-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.notice-date {
  width: 80px;
  text-align: center;
  margin-right: 20px;
  flex-shrink: 0;
}

.day {
  font-size: 28px;
  font-weight: bold;
  color: #1a73e8;
  line-height: 1;
}

.month-year {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.notice-content {
  flex-grow: 1;
  min-width: 0;
}

.notice-title {
  font-size: 18px;
  color: #333;
  margin: 0 0 10px 0;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.notice-text {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.notice-actions {
  flex-shrink: 0;
  margin-left: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

@media (max-width: 768px) {
  .notice-item {
    flex-direction: column;
  }

  .notice-date {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    width: auto;
  }

  .day {
    margin-right: 10px;
  }

  .notice-actions {
    margin-left: 0;
    margin-top: 10px;
    justify-content: flex-end;
  }
}
</style>